<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预约日期" prop="appointDate">
        <el-date-picker clearable
          v-model="queryParams.appointDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择预约日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预约金额(万元)" prop="amount">
        <el-input
          v-model="queryParams.amount"
          placeholder="请输入预约金额(万元)"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户姓名" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="证件号码" prop="idNumber">
        <el-input
          v-model="queryParams.idNumber"
          placeholder="请输入证件号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['proprice:deposit:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['proprice:deposit:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['proprice:deposit:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['proprice:deposit:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="depositList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="产品类型" align="center" prop="productType" />
      <el-table-column label="预约日期" align="center" prop="appointDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.appointDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约金额(万元)" align="center" prop="amount" />
      <el-table-column label="客户姓名" align="center" prop="customerName" />
      <el-table-column label="证件号码" align="center" prop="idNumber" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="附件" align="center" prop="fileUrls" width="220">
        <template slot-scope="scope">
          <el-upload
            v-if="!scope.row.fileUrls"
            class="upload-demo"
            :action="uploadUrl"
            :headers="headers"
            :on-success="(response) => handleUploadSuccess(response, scope.row)"
            :before-upload="beforeUpload"
            :limit="1"
            :show-file-list="false">
            <el-button size="mini" type="primary">上传</el-button>
          </el-upload>
          <div v-else>
            <el-button
              size="mini"
              type="text"
              @click="handleDownload(scope.row)">
              {{ getFileName(scope.row.fileUrls) }}
            </el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              @click="handleRemoveFile(scope.row)"
              v-hasPermi="['proprice:deposit:edit']">
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['proprice:deposit:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['proprice:deposit:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改存款预约登记对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="产品类型" prop="productType">
          <el-select v-model="form.productType" placeholder="请选择产品类型">
            <el-option label="活期存款" value="活期存款" />
            <el-option label="定期存款" value="定期存款" />
            <el-option label="协议存款" value="协议存款" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约日期" prop="appointDate">
          <el-date-picker
            v-model="form.appointDate"
            type="date"
            placeholder="请选择预约日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约金额" prop="amount">
          <el-input-number 
            v-model="form.amount"
            :precision="2"
            :step="1"
            :min="0"
            controls-position="right"
            style="width: 100%">
            <template slot="append">万元</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="客户姓名" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="证件号码" prop="idNumber">
          <el-input v-model="form.idNumber" placeholder="请输入证件号码" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
        <el-form-item label="附件" prop="files">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="headers"
            :on-success="handleFormUploadSuccess"
            :on-remove="handleFormRemove"
            :before-upload="beforeUpload"
            :file-list="fileList"
            :limit="1"
            :on-exceed="handleExceed"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              支持格式：jpg、jpeg、png、gif、doc、docx、xls、xlsx、pdf、zip、rar，单个文件不超过10MB
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDeposit, getDeposit, delDeposit, addDeposit, updateDeposit } from "@/api/proprice/deposit";

export default {
  name: "Deposit",
  data() {
    // 身份证号码验证
    const validateIdNumber = (rule, value, callback) => {
      if (value && !/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value)) {
        callback(new Error('请输入正确的身份证号码'))
      } else {
        callback()
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 存款预约登记表格数据
      depositList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productType: null,
        appointDate: null,
        amount: null,
        customerName: null,
        idNumber: null,
        fileUrls: null,
      },
      // 表单参数
      form: {
        id: undefined,
        productType: undefined,
        appointDate: undefined,
        amount: 0,
        customerName: undefined,
        idNumber: undefined,
        remark: undefined,
        fileUrls: undefined,
        fileNames: undefined
      },
      // 表单校验规则
      rules: {
        productType: [
          { required: true, message: "产品类型不能为空", trigger: "change" }
        ],
        appointDate: [
          { required: true, message: "预约日期不能为空", trigger: "change" }
        ],
        amount: [
          { required: true, message: "预约金额不能为空", trigger: "blur" }
        ],
        customerName: [
          { required: true, message: "客户姓名不能为空", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ],
        idNumber: [
          { required: true, message: "证件号码不能为空", trigger: "blur" },
          { validator: validateIdNumber, trigger: "blur" }
        ]
      },
      // 日期选择器限制选项
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now() // 禁用今天及以前的日期
        }
      },
      fileList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/proprice/deposit/upload',
      headers: {
        Authorization: 'Bearer ' + this.$store.getters.token
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询存款预约登记列表 */
    getList() {
      this.loading = true;
      listDeposit(this.queryParams).then(response => {
        this.depositList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        productType: undefined,
        appointDate: undefined,
        amount: 0,
        customerName: undefined,
        idNumber: undefined,
        remark: undefined,
        fileUrls: undefined,
        fileNames: undefined
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加存款预约登记";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDeposit(id).then(response => {
        this.form = response.data;
        // 如果有附件，初始化文件列表
        if (this.form.fileUrls) {
          this.fileList = [{
            name: this.getFileName(this.form.fileUrls),
            url: process.env.VUE_APP_BASE_API + '/proprice/deposit/download?fileName=' + 
              encodeURIComponent(this.form.fileUrls)
          }];
        }
        this.open = true;
        this.title = "修改存款预约登记";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理文件列表
          if (this.fileList.length > 0) {
            this.form.fileUrls = this.fileList.map(file => file.url).join(',')
          }
          
          if (this.form.id != null) {
            updateDeposit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDeposit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除存款预约登记编号为"' + ids + '"的数据项？').then(function() {
        return delDeposit(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('proprice/deposit/export', {
        ...this.queryParams
      }, `deposit_${new Date().getTime()}.xlsx`)
    },
    // 表单中的文件上传成功回调
    handleFormUploadSuccess(response, file) {
      if (response.code === 200) {
        // 清除之前的文件
        this.fileList = [{
          name: file.name,
          url: response.data.url
        }];
        // 更新表单数据
        this.form.fileUrls = response.data.url;
        this.form.fileNames = file.name;
      } else {
        this.$modal.msgError(response.msg || '上传失败');
      }
    },
    
    // 表单中的文件移除回调
    handleFormRemove(file) {
      this.fileList = [];
      this.form.fileUrls = '';
      this.form.fileNames = '';
    },
    
    // 列表中的文件上传成功回调
    handleUploadSuccess(response, row) {
      if (response.code === 200) {
        // 更新行数据
        const updateData = {
          id: row.id,
          productType: row.productType,
          appointDate: row.appointDate,
          amount: row.amount,
          customerName: row.customerName,
          idNumber: row.idNumber,
          remark: row.remark,
          fileUrls: response.data.url,
          fileNames: response.data.fileName
        };
        
        // 调用更新接口
        updateDeposit(updateData).then(res => {
          if (res.code === 200) {
            this.$modal.msgSuccess("上传成功");
            this.getList();
          } else {
            this.$modal.msgError(res.msg || "更新失败");
          }
        }).catch(err => {
          console.error('Update failed:', err);
          this.$modal.msgError("更新失败：" + (err.msg || err.message || '未知错误'));
        });
      } else {
        this.$modal.msgError(response.msg || '上传失败');
      }
    },
    
    // 删除文件
    handleRemoveFile(row) {
      this.$modal.confirm('是否确认删除该附件？').then(() => {
        const updateData = {
          id: row.id,
          productType: row.productType,
          appointDate: row.appointDate,
          amount: row.amount,
          customerName: row.customerName,
          idNumber: row.idNumber,
          remark: row.remark,
          fileUrls: '',
          fileNames: ''
        };
        
        updateDeposit(updateData).then(res => {
          if (res.code === 200) {
            this.$modal.msgSuccess("删除成功");
            this.getList();  // 刷新列表
          } else {
            this.$modal.msgError(res.msg || "删除失败");
          }
        }).catch(err => {
          console.error('Delete failed:', err);
          this.$modal.msgError("删除失败：" + (err.msg || err.message || '未知错误'));
        });
      }).catch(() => {});
    },
    
    // 下载文件
    handleDownload(row) {
      const url = row.fileUrls;
      if (!url) return;
      
      // 创建a标签下载
      const link = document.createElement('a');
      link.href = process.env.VUE_APP_BASE_API + '/proprice/deposit/download?fileName=' + 
        encodeURIComponent(url);
      
      // 添加认证头
      const token = this.$store.getters.token;
      fetch(link.href, {
        headers: {
          'Authorization': 'Bearer ' + token
        }
      })
      .then(res => res.blob())
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        link.href = url;
        link.download = this.getFileName(row.fileUrls);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      })
      .catch(err => {
        this.$modal.msgError("下载失败");
        console.error(err);
      });
    },
    
    // 获取文件名
    getFileName(url) {
      if (!url) return '';
      const name = url.substring(url.lastIndexOf('/') + 1);
      // 如果文件名包含时间戳前缀，则提取原始文件名部分
      if (name.includes('_')) {
        return name.substring(name.indexOf('_') + 1);
      }
      return name;
    },
    
    // 上传前校验
    beforeUpload(file) {
      const extension = file.name.split('.').pop().toLowerCase();
      const allowedTypes = ['jpg','jpeg','png','gif','doc','docx','xls','xlsx','pdf','zip','rar','txt','pptx','ppt'];
      
      if (!allowedTypes.includes(extension)) {
        this.$message.error('不支持的文件类型');
        return false;
      }
      
      const isLt10M = file.size / 1024 / 1024 < 100;
      if (!isLt10M) {
        this.$message.error('文件大小不能超过100MB');
        return false;
      }
      
      return true;
    },
    
    // 超出数量限制
    handleExceed() {
      this.$modal.msgError('最多只能上传1个文件');
    },
    
    // 编辑时加载文件列表
    loadFileList(fileUrls, fileNames) {
      if (fileUrls && fileNames) {
        const urls = fileUrls.split(',');
        const names = fileNames.split(',');
        this.fileList = urls.map((url, index) => ({
          name: names[index],
          url: url
        }));
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.el-dialog {
  .el-input-number {
    width: 100%;
  }
  
  .upload-demo {
    .el-upload__tip {
      color: #909399;
      font-size: 12px;
      margin-top: 5px;
    }
  }
}

.el-link {
  margin-right: 10px;
}
.el-button [class*="el-icon-"] + span {
  margin-left: 5px;
}

.upload-demo {
  .el-upload {
    margin-bottom: 10px;
  }
  .el-upload__tip {
    line-height: 1.2;
  }
}
</style>
